#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/12 17:55
# @Author : 闫峰
# @File    : ceshi.py
from datetime import datetime

import pymongo

from utils.mysqlUtils.mongodb_utils import MongoDBLink
import os

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])
info_path = ensure_path_sep(f"\\logs\\info-{dis_path}.log")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}.log")
if os.path.exists(info_path):
    os.remove(info_path)
if os.path.exists(error_path):
    os.remove(error_path)
if os.path.exists(warning_path):
    os.remove(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class TestA:

    def test_(self, OrderSourceId):
        modb = MongoDBLink(
            uri='mongodb://rwuser:G1mob8U3VQ1obsFxHClJ!@124.71.9.215:8635,110.41.3.226:8635/?authSource=admin',
            dbname='irobotbox_marketpublish', coll_name='Ap_AutoPublish_Allegro_Listing')
        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")
        # 1 从mongodb筛选出要检查的数据
        start_date = datetime(2023, 10, 10, 0, 0, 0)
        filter = {
            "AddTime": {
                "$gte": start_date
            }
        }

        sql = """
        SELECT a.OrderSourceId,a.OnlineStatus,a.PublishTime,a.Sku,a.ProductId,a.CategoryId
        FROM m_allegro_listing a
        left join m_allegro_listing_sub b
        on a.CustomerId=b.CustomerId and a.OrderSourceId=b.OrderSourceId and a.OfferId=b.OfferId
        WHERE a.OrderSourceId=%s
        AND a.OnlineStatus=1
        AND b.CreationTime >=  DATE_ADD(NOW(),INTERVAL -2 DAY)
        """
        res = znkd_db.fetch_all_tuple(sql, (OrderSourceId,))
        if res:
            # sku_list = [(Sku,ProductId,CategoryId)]
            sku_list = list(map(lambda x: (x[3], x[5], x[4]), res))
            # sku_list = [('17599310', '15979', '14478487207'),('17599311', '15979', '14478487208')]


            # 查询 是否存在同母体下且分类相同的上架的listing

            for skuCategoryIdProductId in sku_list:
                sku = skuCategoryIdProductId[0]
                category = skuCategoryIdProductId[1]
                productid = skuCategoryIdProductId[2]
                # 分类id VariantsByColorPatternAllowed是否为true
                getVariantsByColorPatternAllowed = """
                SELECT VariantsByColorPatternAllowed FROM m_allegro_marketcategory WHERE MarketId=67 AND SiteCode='PL' AND CategoryId=%s
                """
                VariantsByColorPatternAllowed = znkd_db.fetch_all_tuple(getVariantsByColorPatternAllowed, (category,))
                if len(VariantsByColorPatternAllowed):
                    if int.from_bytes(VariantsByColorPatternAllowed[0][0], byteorder='big') == 1:
                        # 查询 是否存在同母体下且分类相同的上架的listing
                        get_ParentId = """
                        select ParentId,IsVariant,IsGroup from p_product WHERE CustomerId=1 AND sku=%s
                        """
                        ParentIdIsVariantIsGroup = znkd_db.fetch_all_tuple(get_ParentId, (sku,))
                        if int.from_bytes(ParentIdIsVariantIsGroup[0][1], byteorder='big') == 1 and int.from_bytes(ParentIdIsVariantIsGroup[0][2], byteorder='big') == 0:
                            # 变体
                            get_sku_List_by_ParentId = """
                            select sku from p_product WHERE CustomerId=1 AND ParentId=%s
                            """
                            sku_List_by_ParentId = znkd_db.fetch_all_tuple(get_sku_List_by_ParentId, (ParentIdIsVariantIsGroup[0][0],))
                            sku_List_by_ParentId_list = list(map(lambda x:x[0],sku_List_by_ParentId))
                            # 如果存在 查询母体下的变体id是否全部为空 如果是 创建变体
                            get_productid_by_sku_category = """
                            SELECT OrderSourceId,OnlineStatus,PublishTime,Sku,ProductId,CategoryId
                            FROM m_allegro_listing 
                            WHERE OrderSourceId=%s
                            AND OnlineStatus=1
                            AND sku=%s
                            AND CategoryId=%s
                            """
                            offer_id_set = set()
                            for sku_other in sku_List_by_ParentId_list:
                                productid_by_sku_category = znkd_db.fetch_all(get_productid_by_sku_category, (OrderSourceId,sku_other,category))
                                if len(productid_by_sku_category):
                                    offer_id_set.add(productid_by_sku_category[0]['ProductId'])

                            if productid in offer_id_set:
                                offer_id_set.remove(productid)
                            if len(offer_id_set):

                                # 将本身的offerid 加入到集合中
                                offer_id_set.add(productid)
                                # 查询所有的listing 变体id 是否为空
                                get_setid_list = """
                                SELECT SetId FROM  m_allegro_listing_sub WHERE CustomerId=1 AND OrderSourceId=%s AND OfferId in %s;
                                """
                                setid_list = znkd_db.fetch_all_tuple(get_setid_list, (OrderSourceId,offer_id_set))
                                setid_set = set(map(lambda x:x[0],setid_list))
                                setid_set1 = set(x for x in setid_set if x is not None)
                                if len(setid_set1):
                                    print()
                                    if len(setid_set1) >1:
                                        INFO.logger.info(f"变体id不相同 不处理")
                                        continue
                                    if len(setid_set1) == 1:
                                        if "None" in setid_set:
                                            INFO.logger.info(f"变体id不相同 不处理")
                                            continue
                                        INFO.logger.info(f"变体id相同,修改变体")

                                else:
                                    # 所有的setid为空
                                    print()
                            else:
                                INFO.logger.info(f"没有查询到其他在线的offer")

                    else:
                        ERROR.logger.error(f"分类的VariantsByColorPatternAllowed！=1")

                elif int.from_bytes(ParentIdIsVariantIsGroup[0][1], byteorder='big') == 0 and int.from_bytes(ParentIdIsVariantIsGroup[0][2], byteorder='big') == 1:
                    # 是组合sku 查询出子sku列表
                    get_sku_List_by_GroupSku = """
                    SELECT sku FROM p_product_groupsku WHERE CustomerId=1 AND GroupSku=%s;
                    """
                    sku_List_by_GroupSku = znkd_db.fetch_all(get_sku_List_by_GroupSku,(sku,))

                    offer_id_set = set()
                    for sku in sku_List_by_GroupSku:
                        sku = sku['sku']
                        offer_id_set.add(sku)
                    if productid in offer_id_set:
                        offer_id_set.remove(productid)
                    if len(offer_id_set):

                        # 将本身的offerid 加入到集合中
                        offer_id_set.add(productid)
                        # 查询所有的listing 变体id 是否为空
                        get_setid_list = """
                        SELECT SetId FROM  m_allegro_listing_sub WHERE CustomerId=1 AND OrderSourceId=%s AND OfferId in %s;
                        """
                        setid_list = znkd_db.fetch_all_tuple(get_setid_list, (OrderSourceId, offer_id_set))
                        setid_set = set(map(lambda x: x[0], setid_list))
                        setid_set1 = set(x for x in setid_set if x is not None)
                        if len(setid_set1):
                            print()
                            if len(setid_set1) > 1:
                                INFO.logger.info(f"变体id不相同 不处理")
                                continue
                            if len(setid_set1) == 1:
                                INFO.logger.info(f"变体id相同,修改变体")

                        else:
                            # 所有的setid为空
                            print()
                    else:
                        INFO.logger.info(f"没有查询到其他在线的offer")

                elif int.from_bytes(ParentIdIsVariantIsGroup[0][1], byteorder='big') == 0 and int.from_bytes(ParentIdIsVariantIsGroup[0][2], byteorder='big') == 0:
                    # 普通sku 查询是不是组合sku的子sku
                    # getGroupSkuBySku = """
                    # SELECT GroupSku FROM p_product_groupsku WHERE CustomerId=1 AND sku=%s;
                    # """
                    # GroupSkuBySku = znkd_db.fetch_all(getGroupSkuBySku,(sku,))
                    pass
                    print()



if __name__ == '__main__':
    TestA().test_(11412)
